# -*- encoding=utf8 -*-

__author__ = "code哥"
import subprocess
from sanic.blueprints import Blueprint
from sanic.views import HTTPMethodView
from sanic import response
from sanic_openapi import doc
from conf.app_list import apps_info
from conn_pool import get_redis

rs = get_redis()

blueprint = Blueprint(__name__, '/api')


class RYMStop(HTTPMethodView):

    @doc.summary("停止媷羊毛主程序")
    def post(self, request):
        # 清空redis
        rs.flushall()
        process = subprocess.Popen("ps -ef | grep start.py | grep -v grep | awk '{print $2}' | xargs kill -TERM",
                                   shell=True, close_fds=True, stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        process.wait()
        # 停止子脚本
        for item in apps_info:
            script = item.get('script', '')
            process_child = subprocess.Popen(
                "ps -ef | grep %s.py | grep -v grep | awk '{print $2}' | xargs kill -TERM" % (script,),
                shell=True, close_fds=True, stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            process_child.wait()
        return response.json({'code': 0, 'data': {'msg': '停止成功'}})


blueprint.add_route(RYMStop.as_view(), '/rym_stop', strict_slashes=True)
